package com.gm.commonlib.network.basenetwork.numberformat;
import com.gm.commonlib.network.basenetwork.util.NetTimeUtils;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

import java.lang.reflect.Type;
import java.util.Date;
import java.util.regex.Pattern;

public class DateDeserializer implements JsonDeserializer<Date> {

    String timeFormat = "\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}";
    public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        String jsonString = "";
        try {
            jsonString = json.getAsString();
            if (jsonString.equals("") || jsonString.equals("null")) {//定义为int类型,如果后台返回""或者null,则返回0
                return null;
            }
        } catch (Exception ignore) {
        }
        try {
            if(Pattern.compile(timeFormat).matcher(jsonString).matches()) {
                return NetTimeUtils.formatDateTime(jsonString, NetTimeUtils.LONG_DATETIME_FORMAT_STRING);
            }
            return new Date(json.getAsJsonPrimitive().getAsLong());
        } catch (Exception e) {
            return null;
        }
    }
}